package com.ngkj.zmfptback.sys.service.write.impl;

import com.ngkj.zmfptback.sys.bean.AuthorityEntity;
import com.ngkj.zmfptback.sys.bean.MenuEntity;
import com.ngkj.zmfptback.sys.mapper.read.AuthReadMapper;
import com.ngkj.zmfptback.sys.mapper.write.AuthWriteMapper;
import com.ngkj.zmfptback.sys.mapper.write.MenuWriteMapper;
import com.ngkj.zmfptback.sys.mapper.write.RoleAuthWriteMapper;
import com.ngkj.zmfptback.sys.service.write.MenuWriteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ChenHN
 * @since 2021/12/22 creation
 **/
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class MenuWriteServiceImpl implements MenuWriteService {

    @Resource
    private MenuWriteMapper menuWriteMapper;

    @Resource
    private AuthWriteMapper authWriteMapper;

    @Resource
    private AuthReadMapper authReadMapper;

    @Resource
    private RoleAuthWriteMapper roleAuthWriteMapper;

    @Override
    public void deleteMenuById(Long id) {
        menuWriteMapper.deleteById(id);
        AuthorityEntity authorityEntity = authReadMapper.getAuthIdByTypeAndFunId("MENU",id);
        long authId = authorityEntity.getId();
        authWriteMapper.deleteAuthById(authId);
        roleAuthWriteMapper.deleteRoleAuthByAuthId(authId);
    }

    @Override
    public void addMenu(MenuEntity menuEntity) {
        menuWriteMapper.addMenu(menuEntity);
        long menuId = menuEntity.getId();
        AuthorityEntity authorityEntity = new AuthorityEntity();
        authorityEntity.setFunId(menuId);
        authorityEntity.setAuthType("MENU");
        authorityEntity.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        authorityEntity.setDescription(menuEntity.getMenuName());
        authWriteMapper.addAuth(authorityEntity);
    }

    @Override
    public void editMenu(MenuEntity menuEntity) {
        menuWriteMapper.updateMenu(menuEntity);
        authWriteMapper.editAuthDescription("MENU",menuEntity.getId(),menuEntity.getMenuName());
    }
}
